#!/usr/bin/env python2.5

# 'Friendly Flow' is a Server Framework for Python 2.5 and up
# Copyright (C) Xaba Software http://www.xaba.nl/
#
# This file is part of 'Friendly Flow'
#
# 'Friendly Flow' is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 'Friendly Flow' is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with 'Friendly Flow'; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from sys import path
path.insert(0, '..')

from socket import SOL_SOCKET, SO_REUSEADDR
from friendlyflow import Scheduler, flatten, socket, fork, HttpRequest

def handleTcp8000(sock, remoteAddress):
    httpRequest = HttpRequest(sock, remoteAddress)
    path = yield httpRequest.path()
    yield httpRequest.writeAll("you requested %s" % path)
    sock.close()

def tcpServer():
    listening = socket()
    listening.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    listening.bind(('0.0.0.0', 8000))
    listening.listen(10)
    while True:
        sock, remoteAddress = yield listening.accept()
        yield fork(flatten(handleTcp8000(sock, remoteAddress)))

def main():
    scheduler = Scheduler([flatten(tcpServer())])
    scheduler.run()

if __name__ == "__main__":
    main()
    
#is it possible to write a yielding for statement?